import Vue from 'vue'
import Vuex from 'vuex'
import axios from "axios";

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        uid: sessionStorage.getItem('uid'),
        uname: sessionStorage.getItem('uname'),
        shopId:'',
        title:'',
        imageUrl:'',
    },
    mutations: {
        setUid(state, uid) {
            state.uid = uid
        },
        setUname(state, uname) {
            state.uname = uname
        },
        setshopId(state,shopId){
            state.shopId=shopId
        },
        setTitle(state,title){
            state.title=title
        },
        setimageUrl(state,imageUrl){
            state.imageUrl=imageUrl
        }
    },
    actions: {
        vlogin(context, form) {
            return new Promise((resolve, reject)=> {
                axios.post('/login',
                    `username=${form.username}&password=${form.pwd}`
                ).then(result => {
                    if (result.data.code == 200) {
                        console.log(result)
                        context.commit("setUid", result.data.result.id);
                        context.commit("setUname", result.data.result.username);
                        sessionStorage.setItem("uname",result.data.result.username)
                        sessionStorage.setItem("uid",result.data.result.id)
                        resolve();
                    } else {
                        console.log(result);
                        reject(result.data)
                    }
                })
            })
        },
        vreg(context,form){
            return new Promise((resolve, reject)=> {
                axios.post('/register',
                    `username=${form.username}&password=${form.pwd}`).then(
                    result => {
                        if (result.data.code == 200) {
                            resolve();
                        } else {
                            reject(result.data);
                        }
                    }
                )
            })
        }
    },
    modules: {}
})
